package com.sharkburner.common.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.sharkburner.common.dao.IGenericDao;

@Repository
public class GenericDao<T> implements IGenericDao<T> {
    private static final Logger LOGGER = Logger.getLogger(GenericDao.class);
    @Autowired
    private HibernateTemplate hibernateTemplate;

    @Override
    public void save(T entity) {
	getHibernateTemplate().save(entity);
    }

    @Override
    public void saveOrUpdate(T entity) {
	getHibernateTemplate().saveOrUpdate(entity);
    }

    @Override
    public void delete(T entity) {
	getHibernateTemplate().delete(entity);
    }

    @Override
    public T get(long id) {
	return getHibernateTemplate().get(getEntityClass(), id);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<T> getAll() {
	String queryString = "FROM " + getEntityClass().getSimpleName();
	List<T> list = new ArrayList<T>();
	list = getHibernateTemplate().find(queryString);
	LOGGER.info("Listed items: " + list.size());
	// Query query = getSession().createQuery(queryString);
	return list;
    }

    @SuppressWarnings("unchecked")
    private Class<T> getEntityClass() {
	return (Class<T>) ((ParameterizedType) getClass()
		.getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public Criteria getCriteria() {
	return getSession().createCriteria(getEntityClass());
    }

    public Session getSession() {
	return getHibernateTemplate().getSessionFactory().getCurrentSession();
    }

    public HibernateTemplate getHibernateTemplate() {
	return hibernateTemplate;
    }

    @Autowired
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
	this.hibernateTemplate = hibernateTemplate;
    }

}
